package com.zone.vehicle.superapp.view.login;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.module.account.entity.LoginEntity;
import com.zone.vehicle.superapp.databinding.FragmentSetCodeBinding;
import com.zone.vehicle.superapp.model.LoginViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.utils.PhoneUtils;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import static com.zone.vehicle.superapp.view.login.LoginFragment.SET_SECRET_FRAGMENT;

public class SetCodeFragment extends BaseFragment {

    private FragmentSetCodeBinding binding;
    private String phone;
    private LoginViewModel viewModel;

    public SetCodeFragment(){

    }

    public void setPhone(String phone){
        this.phone = phone;
        binding.sendPhone.setText("已发送验证码至 "+phone);
    }

    public void setCaptchaCertificate(String captchaCertificate){
        viewModel.getCaptcha_certificate().setValue(captchaCertificate);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentSetCodeBinding.inflate(inflater);
        viewModel = new ViewModelProvider(this, new ViewModelFactory()).get(LoginViewModel.class);
        init();
        return binding.getRoot();
    }

    private void init(){
        binding.numIn1Et.addTextChangedListener(new TextChangeLister(binding.numIn1Et,binding.numIn2Et));
        binding.numIn2Et.setOnKeyListener(new MyOnKeyListenr(binding.numIn1Et, binding.numIn2Et));
        binding.numIn2Et.addTextChangedListener(new TextChangeLister(binding.numIn2Et,binding.numIn3Et));
        binding.numIn3Et.setOnKeyListener(new MyOnKeyListenr(binding.numIn2Et, binding.numIn3Et));
        binding.numIn3Et.addTextChangedListener(new TextChangeLister(binding.numIn3Et,binding.numIn4Et));
        binding.numIn4Et.setOnKeyListener(new MyOnKeyListenr(binding.numIn3Et, binding.numIn4Et));
        binding.numIn4Et.addTextChangedListener(new TextChangeLister(binding.numIn4Et,binding.numIn5Et));
        binding.numIn5Et.setOnKeyListener(new MyOnKeyListenr(binding.numIn4Et, binding.numIn5Et));
        binding.numIn5Et.addTextChangedListener(new TextChangeLister(binding.numIn5Et,binding.numIn6Et));
        binding.numIn6Et.setOnKeyListener(new MyOnKeyListenr(binding.numIn5Et, binding.numIn6Et));
        binding.numIn6Et.addTextChangedListener(new TextChangeLister(binding.numIn6Et, null));
        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
            }
        });
        viewModel.getLoginEntity().observe(getViewLifecycleOwner(), new Observer<LoginEntity>() {
            @Override
            public void onChanged(LoginEntity loginEntity) {
                if (ObjectUtils.isNotEmpty(loginEntity)){
                    changePage(SET_SECRET_FRAGMENT);
                    clean();
                }
            }
        });
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    showLoginFailed(result.getResultMsg());
                }
            }
        });
    }

    class TextChangeLister implements TextWatcher {
        private EditText thisEt,newxtEt;
        public TextChangeLister(EditText thisEt,EditText newxtEt){
            this.thisEt=thisEt;
            this.newxtEt=newxtEt;
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.d(TAG, "beforeTextChanged");
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //text 输入框中改变后的字符串信息
            //start 输入框中改变后的字符串的起始位置
            //before 输入框中改变前的字符串的位置 默认为0
            //count 输入框中改变后的一共输入字符串的数量
            if(before==0&&count==1){
                thisEt.clearFocus();
                if (ObjectUtils.isNotEmpty(newxtEt)) {
                    newxtEt.requestFocus();
                }else {
                    if (checkInput()){
                        String code = binding.numIn1Et.getText().toString()+binding.numIn2Et.getText().toString()+binding.numIn3Et.getText().toString()+binding.numIn4Et.getText().toString()+binding.numIn5Et.getText().toString()+binding.numIn6Et.getText().toString();
                        if (checkPhone(phone) && checkCode(code)){
                            hideInput();
                            viewModel.loginPhoneCodeCheck(getContext(), phone, code);
                        }
                    }
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d(TAG, "afterTextChanged");
        }
    }

    private void clean(){
        viewModel.getLoginEntity().setValue(null);
        binding.numIn1Et.setText("");
        binding.numIn2Et.setText("");
        binding.numIn3Et.setText("");
        binding.numIn4Et.setText("");
        binding.numIn5Et.setText("");
        binding.numIn6Et.setText("");
    }

    private boolean checkInput(){
        if (StringUtils.isNotEmpty(binding.numIn1Et.getText().toString())
            && StringUtils.isNotEmpty(binding.numIn2Et.getText().toString())
            && StringUtils.isNotEmpty(binding.numIn3Et.getText().toString())
            && StringUtils.isNotEmpty(binding.numIn4Et.getText().toString())
            && StringUtils.isNotEmpty(binding.numIn5Et.getText().toString())
            && StringUtils.isNotEmpty(binding.numIn6Et.getText().toString())
        ){
            return true;
        }
        return false;
    }

    private boolean checkPhone(String phone){
        if (!PhoneUtils.isPhoneNum(phone)){
            Toast.makeText(
                    requireContext(),
                    "您填写的手机号码无效，请重新填写",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    private boolean checkCode(String code){
        if (!StringUtils.isNotEmpty(code)){
            Toast.makeText(
                    requireContext(),
                    "请输入验证码",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    //自定义键盘监听
    class MyOnKeyListenr implements View.OnKeyListener {
        private EditText upDt, thisDt;

        public MyOnKeyListenr(@Nullable EditText upDt, @Nullable EditText thisDt) {
            this.upDt = upDt;
            this.thisDt = thisDt;

        }

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            Log.i("键盘监控", "view:" + view + "   i:" + i + "   keyEvent:" + keyEvent.toString());
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_DEL) {  //如果上一个输入框不为空
                if (upDt != null && thisDt.getText().toString().isEmpty()) {
                    thisDt.clearFocus();
                    upDt.requestFocus();
                }
                return false;
            }
            return false;
        }
    }
}